const path = require('path');
const fs = require('fs');
const url = require('url');

const koa = require('koa');
const cors = require('koa-cors');
const favicon = require('koa-favicon');

let app = new koa();

app.use(cors());
app.use(favicon(__dirname + 'favicon.ico'));
app.use(function* (next) {
    let urlObj = url.parse(this.req.url);
    let pathName = urlObj.pathname;

    // 如果用require会有模块缓存的问题
    try {
        let data = fs.readFileSync('./mocks' + pathName + '/default.js');
        let __sendData__ = data.toString();
        __sendData__ = eval(__sendData__);
        this.body = __sendData__;
    } catch ( err ) {
        console.log(err.message);
        this.body = err.message;
    }

    yield next;
});

app.listen(9876, function () {
    console.log('mock 9876')
});